package myJs.cultivars

import myJs.Implicits._
import myJs.myPkg.jquery._
import myJs.myPkg.{ColumnOptions, Select2Options, TableOptions, layer}
import myJs.tool.Pojo.FilterContentData
import myJs.tool.Tool
import org.scalajs.dom.ext.Ajax
import org.scalajs.dom.{Element, document}
import scalatags.Text.all._

import scala.collection.immutable.SeqMap
import scala.concurrent.ExecutionContext.Implicits.global
import scala.scalajs.js
import scala.scalajs.js.Dynamic.{global => g}
import scala.scalajs.js.JSConverters._
import scala.scalajs.js.{JSON, native}
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}

/**
 * Created by yz on 13/11/2020
 */
@JSExportTopLevel("Cultivars")
object Cultivars {

  val tableId = "table"
  val parentId = ""
  var tableRs: JArJDJAn = _

  @JSExport("init")
  def init = {
    initTable
    registerEvent
  }

  def registerEvent = {
    tableFilterEvent

  }

  def tableFilterEvent = {
    Tool.clickHide

    $(document.body).on("click", s".myOperate", "", (y: Element) => {
      Tool.filterContentShow(y, parentId)
    })
    $(document.body).on("click", s".mySortLi", "", (y: Element) => {
      Tool.execSort(y, parentId, () => {
        refreshTable
      })
    })
    $(document.body).on("click", s".myConfirm", "", (y: Element) => {
      Tool.confirmFilter(y, parentId, () => {
        refreshTable
      })
    })
    $(document.body).on("click", s".myHide", "", (y: Element) => {
      Tool.hideFilterContent(y)
    })
    $(document.body).on("click", s".myRemove", "", (y: Element) => {
      Tool.removeCondition(y, parentId, () => {
        refreshTable
      })
    })
    $(document.body).on("click", s".myRemoveSort", "", (y: Element) => {
      Tool.removeSort(y, parentId, () => {
        refreshTable
      })
    })
  }

  def getColumnV(columnName: String, v: js.Any) = columnName match {
    case _ =>
      v.toString
  }

  def refreshTable: Any = {
    refreshTable(() => ())
  }

  def refreshTable(f: () => Any): Any = {
    val queryMap = Tool.getQueryMap("")
    val sortData = Tool.sortExec(tableRs, queryMap)
    val filterData = Tool.execFilter(sortData = sortData, queryMap = queryMap, getColumnV = getColumnV)
    $(s"#${tableId}").bootstrapTable("load", filterData)
    f()
  }

  def tbFmt(columnName: String): js.Function = (v: js.Any, row: js.Dictionary[js.Any]) => columnName match {
    case "Picture" =>
      img(src:=s"/assets/images/${v}.jpg",height:=200)
    case _ => v
  }

  def expStyle(columnName: String): js.Function = (v: js.Any, row: js.Dictionary[Any]) => columnName match {
    case _ => v
  }

  def refreshSelect2(keys: List[String]) = {
    keys.foreach { k =>
      val inputName = k
      val data = tableRs.map(_.myGet(k)).distinct
      val array = data.map { v =>
        js.Dictionary("text" -> v, "id" -> v)
      }
      val options = Select2Options(data=array.toJSArray,multiple=true,placeholder="click to choose")
      Tool.getInputByName(inputName).mySelect2(options)
    }
  }

  def initTable = {
    val index = layer.load(1, Tool.layerOptions.copy(shade=List("0.1", "#fff")))
    val url = g.jsRoutes.controllers.MarkerController.getFileData().url.toString
    Ajax.get(url = s"${url.noCache}&fileName=species.xlsx", headers = Map("Content-Type" -> "application/json")).map { xhr =>
      val rs = xhr.responseText.toJDJAn
      val map = rs("map").toJDS.toSeqMap
      val revMap=map.reverse
      tableRs = rs("array").toJArJDJAn.map { dict =>
        val name = dict.myGet(revMap("Species"))
        val picture = name match {
          case "M. integrifolia" => "Macadamia integrifolia"
          case "M. tetraphylla" => "Macadamia tetraphylla"
          case "M. ternifolia" => "Macadamia ternifolia"
          case "M. jansenii" => "Macadamia jansenii"
        }
        val pictureDict: JDJAn = js.Dictionary("Picture" -> picture)
        (dict ++ pictureDict).toJSDictionary
      }
      val columnNames = map.keyList :+ "Picture"
      val columns = columnNames.map { columnName =>
        val title = map.getOrElse(columnName, columnName)
        val fmt = tbFmt(columnName)
        val style = expStyle(columnName)
        val basicOptions = ColumnOptions.field(columnName).title(title).titleTooltip(title).sortable(false).
          formatter(fmt).cellStyle(style)
        columnName match {
          case _ => basicOptions
        }
      }
      val options = TableOptions.columns(columns.toJSArray).searchOnButton(false).filterControl(false).search(false).
        data(tableRs).pagination(false)
      $(s"#${tableId}").bootstrapTable(options)
      layer.close(index)
      Tool.refreshCheckboxView(map.tail, "checkbox")
      val hideColumns = map.keyList.drop(6)
      hideColumns.foreach { x =>
        $(s"#${tableId}").bootstrapTable("hideColumn", x)
        $(s"input:checkbox[value='${x}']").attr("checked", false)
      }
    }
  }

}
